<template>
	<div class="personalBox">
    <!-- 头部信息 -->
		<div class="card">
			<div class="top">
				<img
					:src="userInfo.headportrait"
					:alt="userInfo.name || '用户头像'"
					class="user-avatar"
				/>

				<div class="tright" v-if="useTokenStore().isLoggedIn">
					<div class="trightt">
						<span>{{ userInfo.name }} </span>
						<span>{{ userInfo.phoneNumber }}</span>
					</div>
					<div class="trightb">
						<img
							class="user-vip__icon"
							src="https://www.finoview.com.cn/images/applet/vip1.png"
						/>
						{{ userInfo.levelName }}
					</div>
					<div class="trightb">有效期至{{ userInfo.expiredate }}</div>
				</div>
			</div>
		</div>
		<div class="basicsBox">
			<el-tabs v-model="activeName" class="tabs">
				<el-tab-pane label="日程" name="rc">
          <Schedule ref="schedule" :teamList="teamList" @showTeam="teamshow=true"/>
        </el-tab-pane>
				<el-tab-pane label="事项" name="sx">
          <template #label>
            <el-badge :value="totalCount" class="item" :max="999">
              <span style="padding-right: 8px;">事项</span>
            </el-badge>
          </template>
          <MenuComponent
            ref="menuRef"
            :menuGroup="menuGroup"
            :myMenuList="myMenuList"
            :menuCountMap="menuCountMap"
            @onSave="handleSaveMyMenu"
            @onItem="handleClickMenuItem"
          />
        </el-tab-pane>
			</el-tabs>
		</div>
    <TeamComponent
      :show="teamshow"
      :list="teamList"
      @onClose="handleCloseTeamShow"
      @onConfirm="handleConfirmTeamShow"
    />
	</div>
</template>

<script setup lang="ts">

import { request } from '@/utils/request'
import MenuComponent from './components/MenuComponent.vue'
import TeamComponent from './components/TeamComponent.vue'
import Schedule from './components/Schedule.vue'
import { getUserInfo, getMemberPower } from '@/miniFile/config/product'
import { computed, onMounted, ref } from 'vue'
import router from '@/router'
import { useTokenStore } from '@/store/modules/tokenStore'


const activeName = ref('rc')
const userInfo = ref({})



const teamshow = ref(false)
const menuGroup = ref([])
const menuCountMap = ref({})
const myMenuList = ref([])

const teamList = ref([])
const powers = ref('')
const menuRef = ref()
const tipsMsg = ref(false)
const totalCount = ref()
const noticeNums = ref([])
const schedule = ref()
// 获取菜单列表
const getMenuList = async () => {
  try {
    const res = await request.post('/api/insure-appsvr/mine/menu/listByGroup')

    console.log('当前菜单信息：', res)

    if (res.data.code === '10000') {
      const { allMenus, myMenus } = res.data.obj
      menuGroup.value = allMenus
      myMenuList.value = myMenus
    } else {
      menuGroup.value = []
      myMenuList.value = []
    }
  } catch (error) {
    console.error('获取菜单失败:', error)
    menuGroup.value = []
    myMenuList.value = []
  }
}

// 保存列表
const saveMyMenuList = (editMyMenuList: any[]) => {
  
  const ids = editMyMenuList.map(item => item.id)
  return request.post('/api/insure-appsvr/mine/menu/saveMyMenu',{ids:ids})
}
const handleSaveMyMenu = async (editMyMenuList: any[]) => {
  const res = await saveMyMenuList(editMyMenuList)
  console.log('res',res);
  
  if (res.status) { 
    myMenuList.value = JSON.parse(JSON.stringify(editMyMenuList))
  } else {
    // ElMessage.error(res.message)
  }

}
const handleClickMenuItem = (menu: any) => {
  const { groupName, name, path, redirectType } = menu

  console.log('groupName, name, path, redirectType',groupName, name, path, redirectType);
  
  // switch (redirectType) {
  //   case 'MINI':
  //     router.push(path)
  //     break
  //   case 'MINI_TAB':
  //     router.replace(path)
  //     break
  //   case 'MINI_FN':
  //     // 执行函数方法
  //     break
  //   case 'WEB':
  //     const url = encodeURIComponent(path)
  //     router.push(`/topicDetail?src=${url}&withToken=1`)
  //     break
  //   default:
  //     break
  // }
}
async function initUser() {
	try {
		const res = await getUserInfo()
		userInfo.value = {
			...res.userInfo,
			headportrait: res.userInfo.headportrait
				? res.userInfo.headportrait
				: 'https://www.finoview.com.cn/images/applet/userImage.jpg',
		}

    useTokenStore().setUserInfo(userInfo.value)
		if (res.status) {
			getMenuList()
			getMenuCount()
			getNoticeNums()
		}
		// getData()
	} catch (error) {}
}
// 初始化权限
const initPower = async () => {
  try {
    const res = await getMemberPower()
    powers.value = res.powers
    console.log('getMemberPower',res);
    
    console.log('useTokenStore()?.userInfo.recommendCode;',useTokenStore()?.userInfo);
    
    if (res.powers.indexOf('12-207') >= 0) {
      if (teamList.value.length === 0) {
        getResearcher()
      }
    }
  } catch (error) {
    console.error('获取权限失败:', error)
  }
}
// 获取团队
const getResearcher = async () => {
  try {
    // 这里需要替换为实际的API调用
    const result = await request.post('/wxapi/appletApi/schedule/getResearcher',{})
    console.log('获取团队',result);
    
    const res = result.data

    if (res.code === 1) {
      let teamListData = [] as any
      const allList = []

      if (res.data && res.data.length > 0) {
        teamListData = allList.concat(res.data)
      }

      teamListData.forEach((teamItem: any) => {
        teamItem.checked = true
      })

      teamList.value = teamListData
    } else if (res.code === 3003) {
      tipsMsg.value = true
    }
  } catch (error) {
    console.error('获取团队数据失败:', error)
  }
}
// 获取菜单待办数量
const getMenuCount = async () => {
  try {
    const response = await request.get('/api/insure-appsvr/mine/menu/countsInfo')

    const res =  response.data

    if (res.code === '10000' && res.obj) {
      menuCountMap.value = res.obj
      totalCount.value = res.total
      console.log('menuCountMap.value',menuCountMap.value);
    } else {
      menuCountMap.value = {}
      totalCount.value = 0
    }
  } catch (error) {
    console.error('获取菜单数量失败:', error)
    menuCountMap.value = {}
    totalCount.value = 0
  }
}
// 获取消息提示数量
const getNoticeNums = async () => {
  try {
    const response = await request.post('/wxapi/appletApi/messageCenter/getUnread',{})

    const res = await response.data

    if (res.code === 1) {
      noticeNums.value = res.data
    }
  } catch (error) {
    console.error('获取消息数量失败:', error)
  }
}

const handleCloseTeamShow = () => {
  teamshow.value = false
}
const handleConfirmTeamShow = () => {
  teamshow.value = false
  schedule.value.getTeamSchedule()
}
onMounted(async ()=>{
  if (useTokenStore().isLoggedIn) {
    await initUser()
    initPower()
  }

})
</script>

<style scoped lang="less">
.personalBox {
	.card {
		margin: 10px 0;
		width: 100%;
		border-radius: 20px;
		padding: 10px 30px;
		box-sizing: border-box !important;
		border: 1px solid rgba(1, 2, 3, 0);
		// background: linear-gradient( 180deg, #EFF6FF 0%, #FBFDFE 100%);
		background-image: url(https://www.finoview.com.cn/images/applet/peoplebg.png);
		background-repeat: no-repeat;
		background-size: 100% 100%;
		.top {
			display: flex;
			padding: 0 0 20px 0;
			> img {
				margin: 20px 15px 0 0;
				width: 60px;
				height: 60px;
				border-radius: 50%;
				object-fit: cover;
				border: 2px solid rgba(255, 255, 255, 0.3);
			}
			.tright {
				width: 100%;
				padding: 15px 0 0 0;
				.trightt {
					display: flex;
					align-items: center;
					margin-bottom: 10px;
					position: relative;
					> :nth-child(1) {
						font-size: 16px;
						color: #0f142c;
						margin-right: 30px;
						font-weight: 600;
					}
					> :nth-child(2) {
						font-size: 14px;
					}
					> :nth-child(3) {
						position: absolute;
						right: 0;
						padding: 4px 8px;
						background-color: @color-1356FF;
						border-radius: 4px;
						font-size: 14px;
						color: white;
						display: flex;
						align-items: center;
						gap: 6px;
					}
				}
				.trightb {
					display: flex;
					align-items: center;
					font-size: 12px;
					color: black;
					margin-bottom: 5px;
				}
			}
		}
	}
}
:deep(.el-tabs__item) {
	font-size: 16px;
	font-weight: 600;
}
</style>
